#!/usr/bin/env python

""" openid.store.dir
"""

from onsocial.lib.base import wsgify, render, webenv
from openid.consumer import consumer
from openid.store.filestore import FileOpenIDStore
from formencode import htmlfill

#from openid.extensions.sreg import SRegRequest, SRegResponse
from openid.sreg import SRegRequest, SRegResponse
from paste.deploy import CONFIG
import webob

from onsocial import model


@wsgify()
def index():
    return render('index.html')

@wsgify()
def login():
    authsession = {}
    store = FileOpenIDStore(CONFIG['openid.store.dir'])
    c = consumer.Consumer(authsession, store)
    passurl = webenv.request.params['passurl']
    authreq = c.begin(passurl)
    authreq.addExtension(SRegRequest(required=['email', 'nickname']))
    authurl = authreq.redirectURL(webenv.request.application_url,
                                  return_to=webenv.request.application_url + '/verify')
    webenv.session['openid.session'] = authsession
    webenv.session.save()
    res = webob.Response(location=authurl,
                         status=302)
    return res

@wsgify()
def verify():
    authsession = webenv.session['openid.session']
    store = FileOpenIDStore(CONFIG['openid.store.dir'])
    c = consumer.Consumer(authsession, store)
    authres = c.complete(webenv.request.str_GET,
                         return_to=webenv.request.application_url + '/verify')

    if authres.status == consumer.SUCCESS:
        sreg_resp = SRegResponse.fromSuccessResponse(authres)
        sreg_args = sreg_resp.getExtensionArgs()
        passurl = authres.identity_url
        webenv.session['openid.sreg.args'] = sreg_args
        webenv.session['openid.identity_url'] = passurl
        webenv.session.save()
        q = model.OpenID.query.filter_by(passurl=passurl)
        if q.count():
            p = q.one()
            webenv.request.environ['REMOTE_USER'] = p.user.nickname
            webenv.session['REMOTE_USER'] = p.user.nickname
            
            return render('index.html')
        else:
            res = webob.Response(location=webenv.request.application_url + '/registration',
                                 status=302)
            return res
    else:
        res = webob.Response(location=webenv.request.application_url,
                             status=302)
        return res
@wsgify()
def signout():
    if 'openid.identity_url' in webenv.session:
        del webenv.session['openid.identity_url']
    if 'REMOTE_USER' in webenv.session:
        del webenv.session['REMOTE_USER']
    res = webob.Response(location=webenv.request.application_url,
                         status=302)
    return res

@wsgify()
def registration_form():
    defaults = webenv.session['openid.sreg.args']
    passurl = webenv.session['openid.identity_url']

    return htmlfill.render(render('registration.html', passurl=passurl),
                           defaults=defaults)


@wsgify()
def registration():
    params = webenv.request.params
    email = params['email']
    nickname = params['nickname']
    u = model.User()
    u.nickname = nickname
    u.email = email
    passurl = webenv.session['openid.identity_url']
    p = model.OpenID()
    p.passurl = passurl
    p.user = u
    model.Session.commit()
    model.Session.remove()
    webenv.request.environ['REMOTE_USER'] = nickname
    webenv.session['REMOTE_USER'] = nickname
    webenv.session['openid.passurl'] = passurl

    res = webob.Response(location=webenv.request.application_url + '/people/' + nickname,
                         status=302)
    return res

    

def routing(app):
    app.add('/', GET=index)
    app.add('/login', POST=login)
    app.add('/verify', GET=verify)
    app.add('/signout', GET=signout)
    app.add('/registration', GET=registration_form, POST=registration)
